package com.miku.blog.utils;

import com.alibaba.fastjson.JSON;
import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.eume.HttpStatusEnum;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author shkstart
 * @create ${}YEAR-05-24 23:58
 */
public class WebUtils {

    public static void sendResponseResult(HttpServletResponse response, AuthenticationException authenticationException){
        ResponseResult responseResult = ResponseResult.error().setMessage(authenticationException.getMessage());
        String jsonString = JSON.toJSONString(responseResult);
        sendString(response,responseResult.getCode(),jsonString);
    }

    public static void sendResponseResult(HttpServletResponse response,HttpStatusEnum httpStatusEnum){
        ResponseResult responseResult = new ResponseResult(httpStatusEnum);
        String jsonString = JSON.toJSONString(responseResult);
        sendString(response,httpStatusEnum.getCode(),jsonString);
    }

    public static void sendString(HttpServletResponse response,Integer code,String msg){

        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(code);
            PrintWriter writer = response.getWriter();
            writer.print(msg);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
